
//
//  DataTools.m
//  BingoWaterfallFlowDemo
//
//  Created by giikylee on 16/5/31.
//  Copyright © 2016年 Bing. All rights reserved.
//

#import "DataTools.h"
#import "AFHTTPRequestOperation.h"
#import "LocationViewController.h"
#import "AFHTTPRequestOperationManager.h"
static DataTools *dataTool = nil;
@implementation DataTools
+(instancetype)shareDataTool
{
    if (dataTool == nil) {
        static dispatch_once_t once_token;
        dispatch_once(&once_token, ^{
            dataTool = [[DataTools alloc]init];
        });
    }
    return dataTool;
}
-(void)getDataWithUrlWithString:(NSString *)Urlstring WithPassValue:(passValue)pass
{
    self.dictionary = [NSDictionary dictionary];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:Urlstring]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;
        NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
        self.dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        pass(self.dictionary);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生错误！%@",error);
    }];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
}
-(void)F_setHttpToJsonDict:(NSString *)url params:(NSDictionary *)params type:(NSString *)type passValue:(passValue)value error:(Error)Error
{
    // 1.创建AFN管理者
    AFHTTPSessionManager *manager = [self managerWithBaseURL:nil sessionConfiguration:NO];
    
    [manager.requestSerializer setValue:@"RbpQ8flsM61Wh6QDB1HCIy2rYMfba626" forHTTPHeaderField:@"appid"];
    [manager.requestSerializer setValue:@"capitalofsouthjadeinchina" forHTTPHeaderField:@"appsecret"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/xml",@"text/plain",@"text/html",@"application/json",@"text/javascript",@"text/javescript",nil];
    
    if ([type isEqualToString:@"F_POST"]) {
        //DoLog(@"请求网址:%@?%@",url,params);
        // 2.发送请求
        [manager POST:url parameters:params  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 请求成功, 通知调用者请求成功
            //NSLog(@"yyyyyyy66   %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
            [self datawithresponseObjectSuccess:responseObject passValue:^(NSDictionary *dict) {
                value(dict);
            } error:^(NSString *error) {
                Error(error);
            }];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self datawithresponseObjectError:error.code error:error Error:^(NSString *error) {
                Error(error);
            }];
        }];
    }
    if ([type isEqualToString:@"F_GET"]) {
        // 2.发送请求
        [manager GET:url parameters:params   success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 请求成功, 通知调用者请求成功
            [self datawithresponseObjectSuccess:responseObject passValue:^(NSDictionary *dict) {
                value(dict);
            } error:^(NSString *error) {
                Error(error);
            }];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self datawithresponseObjectError:error.code error:error Error:^(NSString *error) {
                Error(error);
            }];
        }];
        
    }
}

-(AFHTTPSessionManager *)managerWithBaseURL:(NSString *)baseURL  sessionConfiguration:(BOOL)isconfiguration{
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *manager =nil;
    
    NSURL *url = [NSURL URLWithString:baseURL];
    
    if (isconfiguration) {
        
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
    }else{
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
    }
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    return manager;
}

-(void)datawithresponseObjectSuccess:(id)responseObject passValue:(pushDict)value error:(Error)Error {
    if (responseObject != 0) {
        id dict = [self responseConfiguration:responseObject];
        //DoLog(@"请求成功, 通知调用者请求成功:");
        if ([dict objectForKey:@"Info"] !=nil&[[dict objectForKey:@"Info"] count] !=0) {
            for (NSDictionary *s in [dict objectForKey:@"Info"]) {
                
                if ([s[@"status"] isEqualToString:@"0"]) {
                    value(dict);
                    return ;
                }
            }
            //            DoLog(@"info :%@",dict[@"Info"]);
            //            DoLog(@"info的message:%@",[[dict objectForKey:@"Info"][0] objectForKey:@"message"]);
            //            DoLog(@"info的status:%@",[[dict objectForKey:@"Info"][0] objectForKey:@"status"]);
            NSString * err = [[dict objectForKey:@"Info"][0] objectForKey:@"message"];
            Error(err);
        }else {
            value(dict);
        }
    }else  {
        NSString * err = @"数据为空" ;
        Error(err);
    }
    
}
-(void)datawithresponseObjectError:(NSInteger)code error:(NSError *)error Error:(Error)Error{
    //DoLog(@">>>>%ld通知调用者请求失败的%@" ,error.code,error );
    if (code == -1011) {  Error(@"服务器正在紧急修理,请稍后试一下吧~");
    }else if (code == -1004) {  Error(@"无法连接服务器,请稍后试一下吧~");
    }else{  Error(@"网络连接失败"); }
}
-(id)responseConfiguration:(id)responseObject{
    NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return dic;
}
-(id)responseConfigurationArr:(id)responseObject{
    
    NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return arr;
}

-(void)startLocation
{
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
   // _mapView.showsUserLocation = YES;//显示定位图层
   // _geocodesearch = [[BMKGeoCodeSearch alloc] init];//编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _locService.delegate = self;
    //_geocodesearch.delegate = self;//设置代理为self
}
-(void)sendDataWithStrLat:(NSString *)lat StrLon:(NSString *)lon WithPassValue:(passValue)pass
{
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        //申明返回的结果是json类型
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        //申明请求的数据是json类型
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        //如果报接受类型不一致请替换一致text/html或别的
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/plain",nil];
        //self.strLat = [NSString stringWithFormat:@"%f",[LocationViewController shareLocation].lat];
    
        //传入的参数
        NSDictionary *parameters = @{@"latStr":lat,
                                     @"lngStr":lon};
        //你的接口地址
        NSString *url=@"http://192.168.2.13:8080/shop/store/view";
        //发送请求
        [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"JSON: %@", [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]);
            NSDictionary *dicss = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
            if (pass) {
                pass(dicss);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
}
//-(void)sendDataWithString:(NSString *)url WithPassValue:(passValueArray)pass
//{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    //申明返回的结果是json类型
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    //申明请求的数据是json类型
//    manager.requestSerializer=[AFJSONRequestSerializer serializer];
//    //如果报接受类型不一致请替换一致text/html或别的
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    self.strLat = [NSString stringWithFormat:@"%f",[LocationViewController shareLocation].lat];
//    //传入的参数
//    NSDictionary *parameters = @{@"latStr":@"XXXX",
//                                 @"lngStr":@"XXXX"};
//    //你的接口地址
//   // NSString *url=@"http://192.168.2.14:8080/shop/store/view";
//    //发送请求
//    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"JSON: %@", responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"Error: %@", error);
//    }];
//}
/*-(void)sendDataWithString:(DataModel *)model WithPassValue:(passValueArray)pass
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    //传入的参数
    NSDictionary *parameters = @{@"latStr":@"XXXX",
                                 @"lngStr":@"XXXX"};
    //你的接口地址
    NSString *url=@"http://192.168.2.14:8080/shop/store/view";
    //发送请求
    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}*/


@end
